export class LongPress {
  constructor(time = 800) {
    this.time = time;
    this.longPress = false;
    this.timer = null;
    this.userTimer = null;
    this.vLength = 0;
  }

  onIn() {
    this.longPress = true;
    let hasOnLongPress = typeof this.onLongPress === 'function';
    let hasOnRunning = typeof this.onRunning === 'function' && this.intervalTime >= 24;
    if (hasOnLongPress || hasOnRunning) {
      this.timer = setTimeout(() => {
        if (this.longPress) {
          if (hasOnLongPress) {
            this.onLongPress();
          }
          if (hasOnRunning) {
            this.onRunning();
            this.vLength--;
            if (this.vLength <= 0) {
              return;
            }
            this.__createUserTimer(
              this.onRunning,
              this.intervalTime,
            );
          }
        }

      }, this.time);

    }
  }

  __createUserTimer(callback, intervalTime) {
    this.userTimer = setTimeout(() => {
      callback();
      this.vLength--;
      if (this.vLength > 0) {
        this.__createUserTimer(callback, intervalTime);
      }
    }, intervalTime);
  }

  onOut() {
    this.longPress = false;
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
    this.clearUserInterval();
  }

  clearUserInterval() {
    if (this.userTimer) {
      clearInterval(this.userTimer);
      this.userTimer = null;
    }
  }

  setRunningFunction(onRunning, intervalTime = 24, vLength) {
    this.onRunning = onRunning;
    this.vLength = vLength || 0;
    this.intervalTime = intervalTime;
  }

  setFunction(onLongPress) {
    this.onLongPress = onLongPress;
  }
};
